package cn.tpshion.devops.handle;

import cn.tpshion.devops.common.enums.MsgType;
import cn.tpshion.devops.domain.entity.MsgData;
import cn.tpshion.devops.node.support.NodeContext;
import cn.tpshion.devops.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class LocalCommandHandle {

    private SSEHandle sseHandle;

    private NodeContext nodeContext;

    private String workspace;

    public LocalCommandHandle(SSEHandle sseHandle, NodeContext nodeContext, String workspace){
        this.sseHandle = sseHandle;
        this.nodeContext = nodeContext;
        this.workspace = workspace;
    }

    public void exec(String command) throws Exception{
        if(StringUtils.isBlank(command)){
            return;
        }

        List<String> commandList = new ArrayList<>();
        commandList.add("/bin/sh");
        commandList.add("-c");
        commandList.add(command);

        log.info("LocalCommandHandle commandList:{}", commandList);
        ProcessBuilder processBuilder = new ProcessBuilder(commandList);
        processBuilder.directory(new File(workspace));
        Process process = processBuilder.start();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))){
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("LocalCommandHandle exec log:{}", line);
                sseHandle.sendMessage(nodeContext, new MsgData(MsgType.INFO, line));
            }

            int exitCode = process.waitFor();
            log.info("LocalCommandHandle exec exitCode:{}", exitCode);
            AssertUtil.isTrue(exitCode != 0 && exitCode != -1, "命令执行失败");
        }
    }

}
